<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>拖拽</title>
	<style>
		#box1 {
			width: 100px;
			height: 100px;
			background-color: red;
			position: absolute;
		}

		#box2 {
			width: 100px;
			height: 100px;
			background-color: green;
			position: absolute;
			left: 300px;
			top: 200px;
		}
	</style>
	<script>
    window.onload = () => {
      let box1 = document.getElementById("box1");

      // 鼠标按下绑定move事件
      box1.onmousedown = (event) => {
				// 计算box1 的偏移量
				let x = event.clientX - box1.offsetLeft;
				let y = event.clientY - box1.offsetTop;

				// 移动div的位置
        document.onmousemove = (event) => {
          let left = event.clientX;
          let top = event.clientY;
          box1.style.left = left - x + 'px';
          box1.style.top = top + - y + 'px';
        };

        // 这里要给document绑定, 在页面任意位置
        // 松开按钮都可以取消move事件
        document.onmouseup = () => {
          // 取消move事件
          document.onmousemove = null;
          // onmouseup 也要取消
          document.onmouseup = null;
        }
      };
    };
	</script>

</head>
<body>

<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
